package spring.cloud.tasks.api.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import spring.cloud.tasks.api.service.TaskService;
import spring.cloud.tasks.api.utils.Response;
import spring.cloud.tasks.api.vo.UpdateJobConfigVo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Job config related operations.
 */
@RequestMapping("/console/namespaces/{namespace:.+}/jobs/{jobName}/config")
public class JobConfigController {

    @Resource
    private TaskService jobService;

    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
    @GetMapping
    public Response getTaskConfigurationVo(final HttpServletRequest request,
                                           @PathVariable String namespace,
                                           @PathVariable String jobName) throws RuntimeException {
        return Response.success(jobService.getTaskConfigurationVo(namespace, jobName));
    }

    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})

    @PostMapping
    public Response updateTaskConfiguration(final HttpServletRequest request,
                                            @PathVariable String namespace,
                                            @PathVariable String jobName, UpdateJobConfigVo updateJobConfigVo)
            throws RuntimeException {
        //assertIsPermitted(PermissionKeys.jobUpdate, namespace);
        jobService.updateTaskConfiguration(namespace, updateJobConfigVo.toJobConfig(), getCurrentLoginUserName());
        return new Response();
    }

    private String getCurrentLoginUserName() {
        return null;
    }

    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})

    @PostMapping("/runAtOnce")
    public Response runAtOnce(@PathVariable String namespace,
                              @PathVariable String jobName) throws RuntimeException {
        //assertIsPermitted(PermissionKeys.jobRunAtOnce, namespace);
        jobService.runAtOnce(namespace, jobName);
        return new Response();
    }

    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})

    @PostMapping("/stopAtOnce")
    public Response stopAtOnce(@PathVariable String namespace,
                               @PathVariable String jobName) throws RuntimeException {
        //assertIsPermitted(PermissionKeys.jobStopAtOnce, namespace);
        jobService.stopAtOnce(namespace, jobName);
        return new Response();
    }

}
